<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model="uname" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model.number="age" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="gender">
        <option value="男" name="sex">男</option>
        <option value="女" name="sex">女</option>
      </select>
    </div>
    <div>
      <button @click="addFn">添加/修改</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item, index) in arr" :key="index">
          <td>{{ index + 1 }}</td>
          <td>{{ item.uname }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.gender }}</td>
          <td>
            <button @click="delFn(index)">删除</button>
            <button @click="btnFn(index)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      uname: "",
      age: 0,
      gender: "",
      arr: [
        {
          uname: "张三",
          age: 15,
          gender: "男",
        },
        {
          uname: "李红",
          age: 16,
          gender: "女",
        },
      ],
      bool: true,
      a: null,
    };
  },
  methods: {
    addFn() {
      if (
        this.uname.trim().length === 0 ||
        this.age <= 0 ||
        this.gender.trim().length === 0
      ) {
        return alert("输入有误,请重新输入");
      }
      if (this.bool) {
        this.arr.push({
          uname: this.uname,
          age: this.age,
          gender: this.gender,
        });
        (this.uname = ""), (this.age = 0), (this.gender = "");
      } else {
        (this.arr[this.a].uname = this.uname),
          (this.arr[this.a].age = this.age),
          (this.arr[this.a].gender = this.gender);
        (this.uname = ""), (this.age = 0), (this.gender = "");
        this.bool = true;
      }
    },
    btnFn(index) {
      this.uname = this.arr[index].uname;
      this.age = this.arr[index].age;
      this.gender = this.arr[index].gender;
      this.bool = false;
      this.a = index;
    },
    delFn(index) {
      this.arr.splice(index, 1);
    },
  },
};
</script>
